<?php
/**
 * Anything added to this helper will be available to all templates in the Search controller.
 */
 // http://haugland.ca/guides/34/
 function search_context($string,$query) {
     $buffer         = 100;
     $startPosition  = strpos($string,$query);
     $startPosition -= $buffer;
     if ($startPosition < 0) {
         $startPosition = 0;
     }
     // start at the first word
     $startPosition = strpos(" ",$string);
     $queryLength  = strlen($query);
     $queryLength += $buffer * 2;
     $context      = substr($string,$startPosition,$queryLength);
     
     $pos = strrpos($context, " ");
     if($pos === false) {
         $context = substr($string, $startPosition, $queryLength)."...";
     }
     $context = substr($string, $startPosition, $pos)."...";
          
     return highlight_search_terms($context,$query);
 }
 
 function highlight_search_terms($string, $query)
 {
     $words = explode(" ",$query);
     foreach( $words as $word )
     {
        $string = preg_replace('!('.preg_quote($word).')!i',"<span style='background-color:yellow'>$1</span>",$string);
     }
     return $string;
 }
?>